﻿
Public Class AutoGreyableImage
    Inherits Image

    Shared Sub New()
        ' Override the metadata of the IsEnabled property.
        IsEnabledProperty.OverrideMetadata(GetType(AutoGreyableImage), New FrameworkPropertyMetadata(True, New PropertyChangedCallback(AddressOf OnAutoGreyScaleImageIsEnabledPropertyChanged)))
    End Sub

    Private Shared Sub OnAutoGreyScaleImageIsEnabledPropertyChanged(source As DependencyObject, args As DependencyPropertyChangedEventArgs)
        Dim autoGreyScaleImg As Image = TryCast(source, AutoGreyableImage)
        If autoGreyScaleImg.Source IsNot Nothing Then
            Dim isEnable As Boolean = Convert.ToBoolean(args.NewValue)
            If autoGreyScaleImg IsNot Nothing Then
                If Not isEnable Then
                    Dim bitmapImage As New BitmapImage(New Uri(autoGreyScaleImg.Source.ToString()))
                    autoGreyScaleImg.Source = New FormatConvertedBitmap(bitmapImage, PixelFormats.Gray32Float, Nothing, 0)
                    autoGreyScaleImg.OpacityMask = New ImageBrush(bitmapImage)
                Else
                    autoGreyScaleImg.Source = DirectCast(autoGreyScaleImg.Source, FormatConvertedBitmap).Source
                    autoGreyScaleImg.OpacityMask = Nothing
                End If
            End If
        End If
    End Sub
End Class